package com.atguigu.day03;

import com.atguigu.bean.Event;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink09_TransForm_RichMap {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(3);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);



        //3.将度过来的数据转为Event
        SingleOutputStreamOperator<Event> map = streamSource.map(
//                new MapFunction<String, Event>() {
//
//            @Override
//            public Event map(String value) throws Exception {
//                String[] split = value.split(" ");
//                return new Event(split[0], split[1], Long.parseLong(split[2]));
//            }
//        }
                new MyRichMap()
        );

        map.print();

        env.execute();
    }

    public static class MyRichMap extends RichMapFunction<String,Event>{

        /**
         * 生命周期方法，在算子之前最先调用，在每个并行度上调用一次
         * 适用场景：初始化工作，比如创建连接
         * @param parameters
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("open");
        }

        /**
         * 生命周期方法，在算子最后调用，在每个并行度上调用一次
         * 适用场景：适合做一些清理工作，比如释放连接
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            System.out.println("close");
        }


        @Override
        public Event map(String value) throws Exception {
//            System.out.println(getRuntimeContext().getTaskName());
            //getRuntimeContext可以获取到环境中的信息
            System.out.println(getRuntimeContext().getJobId());
            String[] split = value.split(",");
            return new Event(split[0], split[1], Long.parseLong(split[2]));
        }
    }
}
